package cn.felord.security.autoconfigure.resourceserver;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * @author felord.cn
 * @since 2021/9/7 14:54
 */
@AllArgsConstructor
public class RefreshTokenFilter extends OncePerRequestFilter {
    private static final AntPathRequestMatcher REQUEST_MATCHER = new AntPathRequestMatcher("/token/refresh",
            "POST");
    private final AuthenticationSuccessHandler successHandler;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        if (!REQUEST_MATCHER.matches(request)) {
            filterChain.doFilter(request, response);
            return;
        }
        successHandler.onAuthenticationSuccess(request,response, SecurityContextHolder.getContext().getAuthentication());
    }
}
